package com.aiti.lulian.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CommunicateInfoDto;
import com.aiti.lulian.dto.CommunicateInfoSaveDto;
import com.aiti.lulian.entity.CommunicateInfo;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.ICommunicateInfoService;
import com.aiti.lulian.vo.CommunicateInfoExportVo;
import com.aiti.lulian.vo.CommunicateInfoVo;
import com.aiti.lulian.vo.EmployeeOpportunityCountVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 商机控制层
 */
@Slf4j
@Api(tags = "商机控制层")
@RestController
@RequestMapping("ci")
public class CommunicationInfoController extends WebController {

//    @Autowired
//    private EnterpriseUserService enterpriseUserService;

    private ICommunicateInfoService communicateInfoService;

    public CommunicationInfoController(ICommunicateInfoService communicateInfoService) {
        this.communicateInfoService = communicateInfoService;
    }

    /**
     * 立即沟通
     *
     * @param communicateInfo
     * @return
     */
    @ApiOperation("立即沟通")
    @PostMapping("commitCommunicateInfo")
    public Message commitCommunicateInfo(@RequestBody CommunicateInfo communicateInfo) {
        communicateInfo.setBaseCreateTime(new Date());
        communicateInfo.setBaseId(IdUtil.simpleUUID());

        return communicateInfoService.commitCommunicateInfo(communicateInfo);
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-09-03
     * @Description: 后台新增商机
     */
    @ApiOperation("后台新增商机")
    @PostMapping("/backend/bo")
    public Message addBusinessOpportunity(@Validated @RequestBody CommunicateInfo communicateInfo) {
        try {
            if (communicateInfo == null || BeanUtil.isEmpty(communicateInfo) || StrUtil.isBlank(communicateInfo.getCompanyId())) {
                logger.error("【addBusinessOpportunity】方法新增异常：===》入参异常");
                return Fail("入参异常");
            }
            //检查当前是否已有用户登录
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                communicateInfo.setCreator(userId);
//                //通过远程调用获取该用户的认证企业信息
//                Message message = enterpriseUserService.queryEnterpriseNameByUserId(userId);
//                if (message == null) {
//                    return Fail("获取认证企业信息失败！");
//                }
//                Object obj = message.getObj();
//                if (obj == null) {
//                    return Fail("获取认证企业信息失败！");
//                }
//                if (message.getCode() == 1) {
//                    return Fail(obj);
//                }
//                Map<String, String> queryMap = (Map) obj;
//                String companyId = queryMap.get("baseid");
//                communicateInfo.setCompanyId(companyId);
            } else {
                System.out.println("------------------未登录------------------");
                return Fail("请先登录！");
            }
            //设置类型为后台新增的商机
            communicateInfo.setType("2");
            //进行数据存储
            if (communicateInfoService.save(communicateInfo)) {
                return Success("新增商机成功！");
            } else {
                return Fail("新增商机失败！");
            }
        } catch (Exception e) {
            logger.error("【addBusinessOpportunity】方法新增异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-09-03
     * @Description: 根据baseId查询商机详情
     */
    @ApiOperation("根据baseId查询商机详情")
    @GetMapping("/bo/{baseId}")
    public Message queryBoDetailsByBaseId(@PathVariable("baseId") String baseId) {
        try {
            if (StrUtil.isBlank(baseId)) {
                logger.error("【queryBoDetailsByBaseId】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
//            return Success(communicateInfoService.getById(baseId));
            return communicateInfoService.detailInfo(baseId);
        } catch (Exception e) {
            logger.error("【queryBoDetailsByBaseId】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-09-03
     * @Description: 后台编辑商机
     */
    @ApiOperation("后台编辑商机")
    @PutMapping("/backend/bo")
    public Message updateBusinessOpportunity(@RequestBody CommunicateInfo communicateInfo) {
        try {
            if (communicateInfo == null || BeanUtil.isEmpty(communicateInfo) || StrUtil.isBlank(communicateInfo.getBaseId())) {
                logger.error("【updateBusinessOpportunity】方法更新异常：===》入参异常");
                return Fail("入参异常");
            }
            //判断当前调用为编辑操作时，需要对必填字段进行校验
            if (StrUtil.isBlank(communicateInfo.getIsDel()) && StrUtil.isBlank(communicateInfo.getType())) {
                if (StrUtil.isBlank(communicateInfo.getProductName()) || StrUtil.isBlank(communicateInfo.getCallName()) ||
                        StrUtil.isBlank(communicateInfo.getPhone()) || StrUtil.isBlank(communicateInfo.getCompanyName()) ||
                        StrUtil.isBlank(communicateInfo.getStatus()) || StrUtil.isBlank(communicateInfo.getSalesHeadId())) {
                    return Fail("带*标的为必填项！");
                }
            }
            //检查当前是否已有用户登录
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                communicateInfo.setUpdateBy(userId);
            } else {
                System.out.println("------------------未登录------------------");
                return Fail("请先登录！");
            }
            //进行数据更新
            if (communicateInfoService.updateById(communicateInfo)) {
                return Success("修改商机成功！");
            } else {
                return Fail("修改商机失败！");
            }
        } catch (Exception e) {
            logger.error("【updateBusinessOpportunity】方法更新异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-09-03
     * @Description: 后台查询收到的商机列表
     */
    @ApiOperation("后台查询收到的商机列表")
    @GetMapping("/backend/bo/received/list")
    public Message queryBoReceivedListBackend(Integer pageNum, Integer pageSize, String companyId) {
        try {
            if (pageNum == null || pageSize == null || StrUtil.isBlank(companyId)) {
                logger.error("【queryBoReceivedListBackend】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
            Page<CommunicateInfo> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<CommunicateInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunicateInfo::getType, "1");
            wrapper.eq(CommunicateInfo::getCompanyId, companyId);
            wrapper.eq(CommunicateInfo::getIsDel, "0");
            Page<CommunicateInfo> pageResult = communicateInfoService.page(page, wrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("total", pageResult.getTotal());
            map.put("list", pageResult.getRecords());

            return Success(map);
        } catch (Exception e) {
            logger.error("【queryBoReceivedListBackend】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-09-03
     * @Description: 后台查询全部的商机列表
     */
    @ApiOperation("后台查询全部的商机列表")
    @GetMapping("/backend/bo/all/list")
    public Message queryBoAllListBackend(Integer pageNum, Integer pageSize, CommunicateInfo communicateInfo) {
        try {
            if (pageNum == null || pageSize == null) {
                logger.error("【queryBoAllListBackend】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
            return Success(communicateInfoService.queryBoAllListBackend(pageNum, pageSize, communicateInfo));
        } catch (Exception e) {
            logger.error("【queryBoAllListBackend】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @Author WongMz
     * @CreateDate 2024-09-06
     * @Description: 根据员工ID查询其询盘数
     */
    @ApiOperation("根据员工ID查询其询盘数")
    @GetMapping("/inquiry/{userId}")
    public Message queryInquiryCount(@PathVariable("userId") String userId) {
        try {
            if (StrUtil.isBlank(userId)) {
                logger.error("【queryInquiryCount】方法查询异常：===》入参异常");
                return Fail("入参异常！");
            }
            LambdaQueryWrapper<CommunicateInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommunicateInfo::getSalesHeadId, userId);
            wrapper.eq(CommunicateInfo::getType, "1");
            wrapper.eq(CommunicateInfo::getIsDel, "0");
            int inquiryCount = communicateInfoService.count(wrapper);
            Map<String, Integer> map = new HashMap<>();
            map.put("inquiryCount", inquiryCount);
            return Success(map);
        } catch (Exception e) {
            logger.error("【queryInquiryCount】方法查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /***
     * 查询员工的商机数量
     * @return
     */
    @GetMapping("/queryCommunicateCountList")
    public Message queryCommunicateCountListEmployeeName(CommunicateInfoDto dto){
        String userId = findUserId();
        Integer pageSize = dto.getPageSize();
        Integer pageNum = dto.getPageNum();
        Page<EmployeeOpportunityCountVo> page = this.startPage(pageNum, pageSize);
        List<EmployeeOpportunityCountVo> list = communicateInfoService.queryCommunicateCountList(page,dto,userId);
        return Message.success(getPageResult(list,pageNum, pageSize, (int)page.getTotal()));
    }

    /**
     * 查询已完成、总数、沟通中的数量
     * @return
     */
    @GetMapping("/queryCommunicateCount")
    public Message queryCommunicateCount(CommunicateInfoDto dto){
        String userId = findUserId();
        Map<String, Long> result = communicateInfoService.queryCommunicateCount(userId,dto);
        return Message.success(result);
    }

    @ApiOperation("商机列表分页")
    @GetMapping("/page")
    public Message page(CommunicateInfoDto dto) {
        Page<CommunicateInfoVo> page = startPage(dto);
        return communicateInfoService.listPage(page, dto);
    }

    @ApiOperation("企业名片保存商机")
    @PostMapping("/save")
    public Message save(@Validated @RequestBody CommunicateInfoSaveDto communicateInfoDto) {
        return communicateInfoService.saveCommunicateInfo(communicateInfoDto);
    }

    @ApiOperation("合同确认")
    @PutMapping("/confirm")
    public Message confirm(@RequestBody CommunicateInfoSaveDto communicateInfoDto) {
        return communicateInfoService.confirm(communicateInfoDto);
    }

    @ApiOperation("商机删除")
    @DeleteMapping("/delete")
    public Message delete(@RequestParam("baseId") String baseId) {
        return communicateInfoService.deleteCommunicateInfo(baseId);
    }

    @ApiOperation("是否是部门负责人")
    @GetMapping("/deptAdmin")
    public Message deptAdmin(@RequestParam(value="userId",required = false) String userId) {
        return communicateInfoService.deptAdmin(userId);
    }

    @ApiOperation("商机负责人转交")
    @PutMapping("/dispatch")
    public Message dispatch(@RequestBody CommunicateInfoSaveDto communicateInfoDto) {
        if(StringUtils.isEmpty(communicateInfoDto.getUserId())){
            communicateInfoDto.setUserId(findUserId());
        }
        return communicateInfoService.dispatch(communicateInfoDto);
    }

    @ApiOperation("后台crm列表编辑商机")
    @PutMapping("/updateField")
    public Message updateField(@RequestBody CommunicateInfoSaveDto communicateInfoDto) {
        return communicateInfoService.updateCommunicateInfo(communicateInfoDto);
    }

    @ApiOperation("后台crm列表导入商机")
    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Message importExcel(@ModelAttribute CommunicateInfoSaveDto dto) {
        dto.setUserId(findUserId());
        // 确保文件和其他参数已经正确设置到 dto 中
        if (dto.getFile() == null || dto.getFile().isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        return communicateInfoService.importExcel(dto);
    }


    @ApiOperation("后台crm列表导出商机")
    @GetMapping("/export")
    public void exportExcel (HttpServletResponse response, CommunicateInfoDto communicateInfoDto) throws Exception {
        // 设置响应头，确保浏览器以下载方式处理文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置用户 ID
        communicateInfoDto.setUserId(findUserId());

        // 获取商机列表
        List<CommunicateInfoExportVo> communicateInfoList = communicateInfoService.communicateInfoList(communicateInfoDto);

        // 检查列表是否为空，如果为空则创建一个空列表
        if (communicateInfoList == null || communicateInfoList.isEmpty()) {
            communicateInfoList = Collections.emptyList();
        }

        // 设置文件名，注意需要对中文进行 URL 编码
        String fileName = URLEncoder.encode("商机导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + fileName + ".xlsx\";" +
                        " filename*=UTF-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 写入数据到输出流
        try (

                OutputStream outputStream = response.getOutputStream()
        ) {

            EasyExcel.write(outputStream, CommunicateInfoExportVo.class)
                    .sheet("商机")
                    .registerWriteHandler(new HeaderStyleHandler())
                    .doWrite(communicateInfoList);
        }
    }

    @ApiOperation("企业名片保存商机（免校验）")
    @PostMapping("/business")
    public Message saveNonCheck(@Validated @RequestBody CommunicateInfoSaveDto communicateInfoDto) {
        if (StrUtil.isBlank(communicateInfoDto.getUserId())) {
            communicateInfoDto.setUserId(findUserId());
        }
        return communicateInfoService.saveCommunicateInfoNonCheck(communicateInfoDto);
    }
}